package cn.group.realm;

import cn.group.domain.Permission;
import cn.group.domain.Role;
import cn.group.domain.Teacher;
import cn.group.domain.User;
import cn.group.service.RoleService;
import cn.group.service.TeacherService;
import cn.group.shiro.token.CustomizedToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TeacherRealm extends AuthorizingRealm {

    private TeacherService teacherService;
    private RoleService roleService;

    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
       return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //System.out.println("管理员登陆验证");
        // 1. 把AuthenticationToken转换为CustomizedToken
        CustomizedToken customizedToken = (CustomizedToken) token;
        // 2. 从CustomizedToken中获取username
        String username = customizedToken.getUsername();
        //数据库中根据用户名查询老师用户信息
        Teacher teacher = teacherService.queryByUsername(username);
        //System.out.println("获得的登陆者："+teacher);
        if(teacher == null){
            //老师为空，表明数据库中没有该用户
            throw new UnknownAccountException();
        }
        //获取安全管理中的session对象
        Session session = SecurityUtils.getSubject().getSession();
        //将获得的学生用户对象放入session域中
        session.setAttribute("user",teacher);
        //获取学生用户的密码
        String password = teacher.getPassword();
        //进行账号密码认证
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password,"123");
        return info;
    }
}
